<template>
    <BreadCrumb :list="crumbList"></BreadCrumb>
    <div class="page-edit">
        <el-form ref="editRef" :model="formData" :rules="formRule" :label-width="98" v-loading="loading">
            <el-form-item :label="tips.file" prop="contentId" class="btn-form">
                 <!-- 视频资源 -->
                 <div class="video">
                    <div>
                        <el-button class="srt-el-button srt-el-button-h32 add-btn" @click="handleAdd">{{formData.materialVO?.materialId ? '替换' : '添加'}}{{tips.file}}</el-button>
                        <span class="content-tip" v-if="contentType === 'video'">视频支持上传 wmv, avi, mp4, mov、flv等格式，大小不超过2G；音频支持上传 mp3、wav、wma、ogg、m4a等格式，大小不超过100M；</span>
                        <span class="content-tip" v-else>支持上传PPT、Word、PDF、excel，大小不超过500M</span>
                    </div>
                    <template v-if="formData.materialVO?.materialId && contentType === 'video'">
                        <div class="video-wrapper">
                            <!-- <MaterialResPlayer
                                :height="180"
                                :width="320"
                                :material="formData.materialVO"
                                :video-options="{ autoplay: true, controlBar: {pictureInPictureToggle: false}}"
                            /> -->
                            <div class="video-player" id="player"></div>
                        </div>
                        <div class="time" v-if="formData.unitValue">时长：{{fmtTime(formData.unitValue)}}</div>
                    </template>
                    <div class="file-wrapper" v-if="formData.materialVO?.materialId && contentType !== 'video'">
                        <div class="tag" :class="[formData.materialVO?.materialType]">{{formData.materialVO?.materialFullName}}</div>
                        <div class="size">{{formData.materialVO?.materialSizeFormat}}</div>
                    </div>
                 </div>
            </el-form-item>
            <el-form-item :label="tips.title" prop="contentTitle" class="srt-el-input-item">
                <el-input show-word-limit maxlength="50" type="text" v-model="formData.contentTitle" class="srt-el-input"
                    placeholder="请输入标题，最多50个字" style="width: 915px;">
                </el-input>
            </el-form-item>
            <el-form-item label="文档长度" prop="unitValue" class="srt-el-input-item input-form" v-if="contentType === 'text'">
                <el-select v-model="formData.unit" class="srt-select input-select"
                        placeholder="请选择" popper-class="srt-select-popper" @change="formData.unitValue = ''">
                        <el-option key="1" label="按时长"
                            :value="1" />
                        <el-option key="2" label="按页数"
                            :value="2" />
                </el-select>
                <el-input type="text" v-model="formData.unitValue" class="srt-el-input input-number"
                    :placeholder="formData.unit == 1 ? '请输入时长' : '请输入页数'">
                    <template #suffix>
                        <span class="unit">{{formData.unit == 1 ? '分钟' : '页'}}</span>
                    </template>
                </el-input>
                <span class="content-tip" v-if="contentType === 'text'">说明：文档长度用于计算完成课程的时间，按页数需要乘以10s 或者按时长计算</span>
            </el-form-item>
        </el-form>
        <div class="edit-submit">
            <el-button class="srt-el-button srt-el-button--primary srt-el-button-h32" :disabled="loading" @click="save"
                type="primary">
                保存
            </el-button>
            <el-button class="srt-el-button srt-el-button--cancel srt-el-button-h32" @click="back">取消</el-button>
        </div>
    </div>
    <!-- 素材库 isForciblySelect-->
    <yanxiu-material-dialog
        v-model="addVisible"
        :category="materialConfig.category"
        :mode="1"
        :limitType="materialConfig.limitType"
        :limitSize="listSize"
        previewEnable
        showMyMaterial
        @on-ok="fileInsert"
    />

</template>
<script setup>
import YanxiuMaterialDialog from '@/components/yanxiu-material-dialog.vue';
import BreadCrumb from '@/components/bread-crumb.vue';
import { ref, onMounted, computed, nextTick, onBeforeUnmount } from 'vue';
import { useRoute } from 'vue-router';
import XgPlayer from '@/components/.xgplayer/xgplayer.js';
import { fmtTransTime } from '@/lib/biz-tools.js'


const route = useRoute();

const formRule = ref({
    contentTitle: [
    {
            required: true,
            validator: (rule, value, callback) => {
                let temp = value && value.trim() || '';
                if (temp.length > 50 || temp.length < 2) {
                    callback('请输入2-50个字的标题');
                }else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    contentId: [
        { required: true, message: route.params.type === 'text' ? '请选择文档' : '请选择音视频', trigger: 'none'}
    ],
    unitValue: [
        {
            required: true,
            validator: (rule, value, callback) => {
                let temp = Number(value);
                if(formData.value.unit === 1) {
                    if (!/^[0-9]+(.[0-9]{1})?$/.test(temp) || temp > 120 || temp < 0.5) {
                         callback('请输入0.5-120之间的数，最多1位小数');
                    } else if(!temp){
                       callback(new Error('请输入文档长度'));
                    } else {
                       callback();
                    }
                }
                if(formData.value.unit === 2) {
                    if (!/^\d{1,10}$/.test(temp) || temp > 1000 || temp < 1) {
                        callback('请输入1-1000的整数');
                    } else if(!temp){
                        callback(new Error('请输入文档长度'));
                    } else {
                       callback();
                    }
                }
            },
            trigger: 'blur'
        }
    ]
});

// 面包屑
const crumbList = ref([]);

// 表单对象
const formData = ref({
     unit: 1
});

const tipsMap = {
    'video': {
        title: '音视频标题',
        file: '音视频'
    },
    'text': {
        title: '文档标题',
        file: '文档'
    }
}

// 提示语
const tips = computed(() => {
    let key = route.params.type;
    return tipsMap[key];
})

const contentType = computed(() => {
    return route.params.type;
})

// 素材库限制大小
const listSize = {
    document: 1 * 500 * 1024 * 1024,
    video: 2 * 1024 * 1024 * 1024,
    audio:  1 * 100 * 1024 * 1024,

}

// 素材类型
const materialConfig = computed(() => {
     if(route.params.type === 'video') { // 视频类型
          return {
              category: ['video', 'audio'],
              limitType: {
                   video: ['wmv', 'avi', 'mp4', 'mov', 'flv'],
                   audio: ['mp3', 'wma', 'flac', 'm4a', 'ogg', 'ape', 'amr', 'wav', 'aac', 'aiff', 'caf']
              },
          }
     }
     return {
         category: ['document'],
         limitType: {
             document: ['doc', 'docx', 'ppt', 'pptx', 'txt', 'xls', 'xlsx', 'pdf', 'rtf', 'odt'],
         }
     }
})


// 素材库对话框
const addVisible = ref(false);

// 选择素材
async function fileInsert(fileList) {
    let isInit = true;
    if(formData.value?.materialVO?.materialId) {
        isInit = false;
    }
    if (!fileList[0]) {
        return;
    }
    formData.value.materialVO = fileList[0];
    formData.value.contentId = fileList[0].materialId;
    formData.value.unitValue = fileList[0].duration;
    formData.value.contentTitle = fileList[0].materialName;
    if(contentType.value === 'video' ) {
        player && player.destroy(false);
        await nextTick();
        setTimeout(() => {
            initPlayer(formData.value.materialVO);
        }, 100)
        // if(isInit) {
        //     initPlayer(formData.value.materialVO);
        // }else {
        //     changeVideoSrc(formData.value.materialVO)
        // }
    }
}

// 添加视频
function handleAdd() {
    addVisible.value = true;
}

let player = null;

// 初始化视频
async function initPlayer(videoData) {
    let videoObj = {
        // autoplay: false,
        el: document.querySelector('#player'),
        url: videoData.transferFileUrl || videoData.materialUrl,
        poster: videoData.snapshotCover,
        fluid: true,
        closeFocusVideoFocus: true,
        closePlayVideoFocus: true,
        // pip: true,
        definitionActive: 'hover',
        volume: 0.3,
        autoplay: true
    }
    player = new XgPlayer(videoObj);
    player.player.once('complete', () => {
        setTimeout(() => {
            // 视频总时长
            console.log('time', player.player.duration)
            formData.value.unitValue = player.player.duration;
        }, 500);
    })
}


async function changeVideoSrc(videoData) {
    await nextTick();
    player.player.src = videoData.transferFileUrl || videoData.materialUrl;
    player.player.poster = videoData.snapshotCover;
    player.player.once('complete', () => {
        setTimeout(() => {
            // 视频总时长
            console.log('time', player.player.duration)
            formData.value.unitValue = player.player.duration;
        }, 500);
    })
}

// 格式化时间
function fmtTime(val = 0) {
    return fmtTransTime(val);
}

const editRef = ref(null);

// 提交保存
function save() {
    if (moocDetail.value.publishState === 1) {
        G_dispatchEvent('toast', { message: '课程已发布，请取消发布后再操作', type: 'error' })
        return;
    }
    editRef.value.validate((valid) => {
        if(!valid) {
            return;
        }
        if(!formData.value.unitValue && contentType.value === 'video') {
            G_dispatchEvent('toast', { message: '请等待音视频加载结束后点击保存', type: 'error'});
            return;
        }
        loading.value = true;

        let params = {
            contentTitle: formData.value.contentTitle,
            unitValue: contentType.value === 'text' && formData.value.unit === 1 ? formData.value.unitValue * 60 : formData.value.unitValue,
            contentId: formData.value.materialVO.materialId,
            unit: formData.value.unit || 1,
            tag: formData.value.materialVO.materialType,
            contentType: 'material'
        }

        if(route.params.catalogueId) {
            params.id = route.params.catalogueId;
            params.courseWareId = formData.value.courseWareId;
        }

        G_transmit('courseContentCreate', {
            data: {
                contentList: [
                    {
                        ...params
                    }
                ],
                courseId: route.params.courseId,
                pid: route.query.pid
            }
        })
        .then((res) => {
            let tip = route.name === 'editContent' ? '编辑成功' : '添加成功';
            G_dispatchEvent('toast', { message: tip, type: 'success'});
            back();
        })
        .catch((_err) => {
            console.log(_err)
        }).finally(() => {
            loading.value = false;
        });
    })
    
}



const loading = ref(false);

function getDetail() {
    loading.value = true;
    G_transmit('courseContentDetail', {
        queries: {
            id: route.params.catalogueId
        }
    }).then(async (res) => {
        formData.value = res.data || {};
        formData.value.unitValue = contentType.value === 'text' && formData.value.unit === 1 ? formData.value.unitValue/60 : formData.value.unitValue;
        if(formData.value?.materialVO?.materialType === 'video' || formData.value?.materialVO?.materialType === 'audio') {
            await nextTick();
            initPlayer(formData.value.materialVO);
        }
    }).catch((_err) => {
        console.log(_err)
    }).finally(() => {
        loading.value = false;
    });
}

// 返回
function back() {
    let name = crumbList.value[0].route;
    G_go(name);
}


// 获取目录名称
function getFolderByIds() {
    G_transmit('getFolderByIds', {
        data: {
           catalogueIdList: [route.query.pid], // 课程id
        },
        silence: true
    }).then((res) => {
        let data = res.data?.length && res.data[0] || {};
        let breadList = getBreadList();
        breadList[0].name = data.catalogueName;
        crumbList.value = breadList;
    }).catch(_err => {
        console.log(_err);
    })
}

// 获取面包屑数据
function getBreadList () {
    let breadRoute = {};
    if(route.query.from === 'editDesign') {
        breadRoute = {
            name: 'editDesign',
            params: {
                courseId: route.params.courseId,
            },
            query: {
                step: 2,
                ...route.query
            }
        }
    }else {
        breadRoute = {
            name: 'design',
            query: {
                courseId: route.params.courseId,
                step: 2,
                ...route.query
            }
        }
    }

    return [
        {
            name: '',
            route: breadRoute,
        },
        {
            name: route.name === 'editContent' ? `编辑${tips.value.file}` : `添加${tips.value.file}`,
            route: {
                name: '',
            }
        }
    ]
}

// 课程详情
const moocDetail = ref({});

function getCourseDetail () {
    G_transmit('courseDetail', {
        queries: {
           id: route.params.courseId
        },
        silence: true
    })
    .then((res) => {
        moocDetail.value = res.data || {};
    })
    .catch((err) => {
        console.log(err)
    })
}


onMounted(() => {
    getFolderByIds();
    if(route.params.catalogueId) {
        getDetail();
    }
    getCourseDetail();
})

onBeforeUnmount(() => {
    player && player.destroy(false);
    // player && player.pause();
})

</script>

<style lang="scss" scoped>

@mixin img-style(){
    content: '';
    width: 18px;
    height: 18px;
    display: inline-block;
    vertical-align: middle;
    transform: translateY(-1px);
    margin-right: 4px;
}

.page-edit {
    background: #ffffff;
    padding: 30px;
    min-height: 700px;

    :deep(.el-form-item) {
        margin-bottom: 30px;
    }

    :deep(.el-form-item__label) {
        line-height: 40px;
        height: 40px;
        color: var(--srt-color-gray);
        margin-right: 8px;
    }

    .btn-form {
        :deep(.el-form-item__label) {
            line-height: 32px;
            height: 32px;
        } 
        .add-btn {
            width: 100px;
        }
    }

    .input-width {
        width: 915px;
    }
    
    .video-wrapper {
        height: 180px;
        width: 320px;
        margin-top: 20px;
        position: relative;
        .video-player {
            height: 180px;
            width: 320px;
        }
    }
    .video {
        .time {
            font-size: 14px;
            color: var(--srt-color-gray);
            margin-top: 12px;
            line-height: 1;
            &::before {
                content: '\e6bb';
                font-family: 'iconfont';
                margin-right: 6px;
                font-size: 16px;
                display: inline-block;
                vertical-align: middle;
                transform: translateY(-1px);
            }
        }
    }

    .edit-submit {
        padding-left: 86px;
        padding-top: 10px;
        .btn {
            width: 76px;
        }
    }
}

.input-form {
    .input-select {
        height: 40px;
        width: 100px;
        min-height: 40px;
        :deep(.el-input) {
             height: 40px;
        }
        :deep(.el-input__wrapper) {
             border-radius: 4px 0px 0px 4px;
        }
    }
    .input-number {
        height: 40px;
        width: 180px;
        margin-left: -1px;
        :deep(.el-input__wrapper) {
            border-radius: 0px 4px 4px 0px;
        }
        .unit {
            color: var(--srt-color-gray);
        }
    }
}
.file-wrapper {
    width: 340px;
    background: #F7F9FA;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 12px 12px 14px;
    margin-top: 20px;
    .size {
        padding-left: 24px;
        line-height: 1;
        margin-top: 10px;
        color: var(--srt-color-gray);
    }
    .tag {
        font-size: 14px;
        color: var(--srt-main-text-color);
        overflow: hidden;
        line-height: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;

        &.doc, &.docx {
            &::before {
                @include img-style();
                background: url('~@/assets/img/resource-type/doc.png') no-repeat;
                background-size: contain;
            }
        }
        &.ppt, &.pptx {
            &::before {
                @include img-style();
                background: url('~@/assets/img/resource-type/ppt.png') no-repeat;
                background-size: contain;
            }
        }
        &.xls, &.xlsx{
            &::before {
                @include img-style();
                background: url('~@/assets/img/resource-type/excel.png') no-repeat;
                background-size: contain;
            }
        }
        &.pdf {
            &::before {
                @include img-style();
                background: url('~@/assets/img/resource-type/pdf.png') no-repeat;
                background-size: contain;
            }
        }

        &.files {
            &::before {
                @include img-style();
                background: url('~@/assets/img/resource-type/files.png') no-repeat;
                background-size: contain;
            }
        }

        &.rest,
        &.unknown {
            &::before {
                @include img-style();
                background: url('~@/assets/img/resource-type/rest.png') no-repeat;
                background-size: contain;
            }
        }
    }
}
.content-tip {
    font-size: 12px;
    color: var(--srt-color-light-gray);
    margin-left: 16px;
}
</style>